package com.im.common.toolkit.http;

import com.im.common.toolkit.CommonUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** @author gongym */
@Log4j2
public class HttpClientUtils {

  @SuppressWarnings("Duplicates")
  @Deprecated
  public static String doPostRequest(
      String url, Map<String, String> header, Map<String, Object> params, HttpEntity httpEntity) {
    String resultStr = "";
    if (CommonUtils.isEmpty(url)) {
      return resultStr;
    }
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
      httpClient = SslClientCustom.getHttpClient();
      HttpPost httpPost = new HttpPost(url);
      // 请求头header信息
      if (CommonUtils.isNotEmpty(header)) {
        for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
          httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
      }
      // 请求参数信息
      if (CommonUtils.isNotEmpty(params)) {
        List<NameValuePair> paramList = new ArrayList<>();
        for (Map.Entry<String, Object> stringStringEntry : params.entrySet()) {
          paramList.add(
              new BasicNameValuePair(
                  stringStringEntry.getKey(), stringStringEntry.getValue().toString()));
        }
        UrlEncodedFormEntity urlEncodedFormEntity =
            new UrlEncodedFormEntity(paramList, Consts.UTF_8);
        httpPost.setEntity(urlEncodedFormEntity);
      }
      // 实体设置
      if (httpEntity != null) {
        httpPost.setEntity(httpEntity);
      }

      // 发起请求
      httpResponse = httpClient.execute(httpPost);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity httpResponseEntity = httpResponse.getEntity();
        resultStr = EntityUtils.toString(httpResponseEntity);
        log.info("请求正常,请求地址:{},响应结果:{}", url, resultStr);
      } else {
        StringBuffer stringBuffer = new StringBuffer();
        HeaderIterator headerIterator = httpResponse.headerIterator();
        while (headerIterator.hasNext()) {
          stringBuffer.append("\t");
          stringBuffer.append(headerIterator.next());
        }
        log.info(
            "异常信息:请求地址:{},响应状态:{},请求返回结果:{}",
            url,
            httpResponse.getStatusLine().getStatusCode(),
            stringBuffer);
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      HttpClientUtils.closeConnection(httpClient, httpResponse);
    }
    return resultStr;
  }

  @SuppressWarnings("Duplicates")
  public static String doGetRequest(
      String url, Map<String, String> header, Map<String, Object> params) {
    String resultStr = "";
    if (StringUtils.isEmpty(url)) {
      return resultStr;
    }
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
      httpClient = SslClientCustom.getHttpClient();
      // 请求参数信息
      if (CommonUtils.isNotEmpty(params)) {
        url = url + buildUrl(params);
      }
      HttpGet httpGet = new HttpGet(url);
      RequestConfig requestConfig =
          RequestConfig.custom()
              .setConnectTimeout(60000)
              .setConnectionRequestTimeout(60000)
              .setSocketTimeout(60000)
              .setRedirectsEnabled(true)
              .build(); // 允许重定向
      httpGet.setConfig(requestConfig);
      if (CommonUtils.isNotEmpty(header)) {
        for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
          httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
      }
      // 发起请求
      httpResponse = httpClient.execute(httpGet);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == HttpStatus.SC_OK) {
        resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
        log.info("请求地址:{},响应结果:{}", url, resultStr);
      } else {
        StringBuffer stringBuffer = new StringBuffer();
        HeaderIterator headerIterator = httpResponse.headerIterator();
        while (headerIterator.hasNext()) {
          stringBuffer.append("\t");
          stringBuffer.append(headerIterator.next());
        }
        log.info(
            "异常信息:请求响应状态:{},请求返回结果:{}", httpResponse.getStatusLine().getStatusCode(), stringBuffer);
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      HttpClientUtils.closeConnection(httpClient, httpResponse);
    }
    return resultStr;
  }

  @SuppressWarnings("Duplicates")
  public static void downloadImage(
      String imgUrl, Map<String, String> header, Map<String, Object> params, String savePath) {
    if (StringUtils.isEmpty(imgUrl)) {
      return;
    }
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
      httpClient = SslClientCustom.getHttpClient();
      // 请求参数信息
      if (CommonUtils.isNotEmpty(params)) {
        imgUrl = imgUrl + buildUrl(params);
      }
      HttpGet httpGet = new HttpGet(imgUrl);
      HttpHost proxy = new HttpHost("127.0.0.1", 1080);
      RequestConfig requestConfig =
          RequestConfig.custom()
              .setProxy(proxy)
              .setConnectTimeout(30000)
              .setConnectionRequestTimeout(30000)
              .setSocketTimeout(30000)
              .setRedirectsEnabled(true)
              .build(); // 允许重定向
      httpGet.setConfig(requestConfig);
      if (CommonUtils.isNotEmpty(header)) {
        for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
          httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
      }
      // 发起请求
      httpResponse = httpClient.execute(httpGet);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity entity = httpResponse.getEntity();
        InputStream in = entity.getContent();
        FileUtils.copyInputStreamToFile(in, new File(savePath));
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      HttpClientUtils.closeConnection(httpClient, httpResponse);
    }
  }

  /** 关掉连接释放资源 */
  private static void closeConnection(
      CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
    if (httpClient != null) {
      try {
        httpClient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (httpResponse != null) {
      try {
        httpResponse.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  private static String buildUrl(Map<String, Object> map) {
    if (CommonUtils.isEmpty(map)) {
      return "";
    }
    StringBuilder stringBuffer = new StringBuilder("?");
    for (Map.Entry<String, Object> stringStringEntry : map.entrySet()) {
      stringBuffer
          .append(stringStringEntry.getKey())
          .append("=")
          .append(stringStringEntry.getValue())
          .append("&");
    }
    String result = stringBuffer.toString();
    if (CommonUtils.isNotEmpty(result)) {
      result = result.substring(0, result.length() - 1);
    }
    return result;
  }
}
